package com.edu.fafu.studentrepair;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.GestureDetector;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.edu.fafu.studentrepair.command.Dictionary;
import com.edu.fafu.studentrepair.command.LocalDataStream;
import com.edu.fafu.studentrepair.fragments.ApplyFragement;
import com.edu.fafu.studentrepair.fragments.ApplyPublicFragment;
import com.edu.fafu.studentrepair.fragments.HumanInfoFragement;
import com.edu.fafu.studentrepair.fragments.Human_pwd_change;
import com.edu.fafu.studentrepair.fragments.RecordFragment;
import com.edu.fafu.studentrepair.fragments.RecordItemFragment;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    //底部导航
    private BottomNavigationView bottomNavigationView;
    private RecordFragment runnningFragment;
    private RecordFragment historyFragment;
    private ApplyFragement applyFragement;
    private RecordFragment refuseFragment;
    private HumanInfoFragement humanInfoFragement;
    private Human_pwd_change human_pwd_change;
    private RecordItemFragment recordItemFragment;
    private ApplyPublicFragment applyPublicFragment;
    private Fragment fragments[];
    private int lastfragment;//用于记录上个选择的Fragment
    private GestureDetector gestureDetector;
//    配置的滑动距离，大于这个做出响应
    protected static final float FLIP_DISTANCE = 50;
    private TextView left_userName;
    private TextView left_userstate;
    private ImageView left_userpic;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        lastfragment = getIntent().getIntExtra("pageIndex",0);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        initFragment();
        //初始化头像和使用状态
        View view = navigationView.getHeaderView(0);
        left_userpic = view.findViewById(R.id.left_userpic);
        left_userName = view.findViewById(R.id.left_userName);
        left_userstate = view.findViewById(R.id.left_userstate);
        try {
            String info = LocalDataStream.read(openFileInput("data"));
            String state = info.split("_")[3];
            String picurl = info.split("_")[4];
            if(state.equals("1")) left_userstate.setVisibility(View.GONE);//没被禁用
            if(!picurl.equals("null")) Glide.with(this).load(picurl).into(left_userpic);//设置头像
            left_userName.setText(info.split("_")[5]);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
//        item.setCheckable(true);//设置选项可选
//        item.setChecked(false);//设置选型被选中
        if (id == R.id.left_human_info) {
            if(lastfragment!=4){ //中心
                switchFragment(lastfragment,4);
                lastfragment=4;
            }
        } else if (id == R.id.left_running) {
            if(lastfragment!=0){ //进行
                switchFragment(lastfragment,0);
                lastfragment=0;
            }
        } else if (id == R.id.left_history) {
            if(lastfragment!=1){ //历史
                switchFragment(lastfragment,1);
                lastfragment=1;
            }
        } else if (id == R.id.left_refuse) {
            if(lastfragment!=3){ //拒绝
                switchFragment(lastfragment,3);
                lastfragment=3;
            }
        }else if(id == R.id.letf_log_out){
                logout();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //初始化fragment
    private void initFragment(){
//        fragmentTest = new FragmentTest();
//        recordFragment = new RecordFragment();
        runnningFragment = new RecordFragment("(1,2,3)");//未读，未处理，处理中
        historyFragment = new RecordFragment("(0)");//历史
        applyFragement = new ApplyFragement();
        refuseFragment = new RecordFragment("(4)");//被拒
        humanInfoFragement = new HumanInfoFragement();
        human_pwd_change = new Human_pwd_change();
        recordItemFragment = new RecordItemFragment();
        applyPublicFragment = new ApplyPublicFragment();
        fragments = new Fragment[]{runnningFragment,historyFragment,applyFragement,refuseFragment,humanInfoFragement,human_pwd_change,recordItemFragment,applyPublicFragment};
//        fragments = new Fragment[]{test_fragment,historyFragment,applyFragement,refuseFragment,humanInfoFragement};
        getSupportFragmentManager().beginTransaction().replace(R.id.mainview,fragments[lastfragment]).show(fragments[lastfragment]).commit();
        bottomNavigationView=findViewById(R.id.bnv);

        bottomNavigationView.setOnNavigationItemSelectedListener(changeFragment);
    }

    //判断选择的菜单
    private BottomNavigationView.OnNavigationItemSelectedListener changeFragment= new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()){
                case R.id.id1:
                    if(lastfragment!=0){ //进行
                        switchFragment(lastfragment,0);
                        lastfragment=0;
                    }
                    return true;
                case R.id.id2:
                    if(lastfragment!=1){ //历史
                        switchFragment(lastfragment,1);
                        lastfragment=1;
                    }
                    return true;
                case R.id.id3:
                    if(lastfragment!=2){ //申报
                        switchFragment(lastfragment,2);
                        lastfragment=2;
                    }
                    return true;
                case R.id.id4:
                    if(lastfragment!=3){ //拒绝
                        switchFragment(lastfragment,3);
                        lastfragment=3;
                    }
                    return true;
                case R.id.id5:
                    if(lastfragment!=4){ //中心
                        switchFragment(lastfragment,4);
                        lastfragment=4;
                    }
                    return true;
                }
            return false;
        }
    };
    //切换Fragment
    public void switchFragment(int lastfragment,int index){
        FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastfragment]);//隐藏上个Fragment
        if(fragments[index].isAdded()==false){
            transaction.add(R.id.mainview,fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
    }

    public void setLastfragment(int lastfragment) {
        this.lastfragment = lastfragment;
    }

    public int getLastfragment() {
        return lastfragment;
    }

    public void setRecordId(Integer recordId){
        ((RecordItemFragment)fragments[Dictionary.Page.FRAGMENT_RECORD_ITEM]).setRecordId(recordId);
    }

    private void logout(){
        Log.i("logout", "logout: 123");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("是否确认退出");

        builder.setPositiveButton("取消", null);
        builder.setNeutralButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    FileOutputStream out = openFileOutput("data", Context.MODE_PRIVATE);
                    LocalDataStream.writer("",out);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                //清空本地账号信息；
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
        WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
        layoutParams.width = 700;
        dialog.getWindow().setAttributes(layoutParams);
    }
}
